package com.slipper.filter;

import com.slipper.exception.CommonException;
import com.slipper.util.Tool;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpRequestCorsFilter implements Filter {
    private final Map<String, String> headerMap = new HashMap<>();

    public HttpRequestCorsFilter(String responseHeader) {
        try {
            if (Tool.isNotBlank(responseHeader)) {
                String[] headers = responseHeader.split(",");
                for (String header : headers) {
                    if (Tool.isBlank(header)) continue;
                    String[] item = header.split("=", 2);
                    if (item.length < 2) continue;
                    headerMap.put(item[0].trim(), item[1].trim());
                }
            }
        } catch (Exception e) {
            throw new CommonException("response.header参数设置错误！", e);
        }
    }

    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = ((HttpServletRequest) servletRequest);
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        headerMap.forEach(response::setHeader);

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
